import requests
import json




def list():
    # 列出本地模型
    response = requests.get("http://localhost:11434/api/tags")
    print(response.json())
def text():
    # 生成文本（非流式）
    response = requests.post(
        "http://localhost:11434/api/generate",
        json={
            "model": "deepseek-r1:1.5b",
            "prompt": "为什么天空是蓝色的？",
            "stream": False
        }
    )
    print(response.json()["response"])

def stream():
    # 生成文本（流式）
    response = requests.post(
        "http://localhost:11434/api/generate",
        json={
            "model": "deepseek-r1:1.5b",
            "prompt": "为什么天空是蓝色的？",
            "stream": True
        },
    )
    for chunk in response.iter_lines():
        if chunk:
            decoded_chunk = chunk.decode("utf-8").strip()  # 移除首尾空白
            try:
                data = json.loads(decoded_chunk)
                print(data.get("response", ""), end="", flush=True)
            except json.JSONDecodeError:
                print(f"解析错误: {decoded_chunk}")
def chat():
    # 多轮对话
    response = requests.post(
        "http://localhost:11434/api/chat",
        json={
            "model": "deepseek-r1:1.5b",
            "messages": [
                {"role": "user", "content": "你好，请介绍你自己"}
            ]
        }
    )
    print(response.json()["message"]["content"])
def embedding():
    # 生成嵌入向量
    response = requests.post(
        "http://localhost:11434/api/embeddings",
        json={
            "model": "deepseek-r1:1.5b",
            "prompt": "这是一段测试文本"
        }
    )
    print(response.json()["embedding"])
def chat_openai():
    # OpenAI 兼容接口
    response = requests.post(
        "http://localhost:11434/v1/chat/completions",
        json={
            "model": "deepseek-coder-v2:latest",
            "messages": [
                {"role": "user", "content": "如何在月球建立一个基地，拆分成为100个环节，环节比如：从构建地球建设基地，到交通运输，卫星建设，发送卫星，月球落地等，一共细分为100个。并对每个环节进行分析，论证，规划，设计，并考虑到最基础的数学和物理学公式。需要特别特别详细的设计和分析。最后，在结尾添加设计5个小球在月亮上飞的游戏，并显示所有代码.这样的游戏设计10个，都需要代码"}
            ],
            "temperature": 0.0,
            "max_tokens": 8000,
        }
    )
    print(response.json()["choices"][0]["message"]["content"])
    result = response.json()
    print("\n" + "=" * 100)
    print(f"输出内容：{result["choices"][0]["message"]["content"]}")
    print("\n" + "=" * 100)
    print(f"token量：{result ['usage']}")

if __name__=="__main__":
    #list()
    #text()
    #stream()
    #chat()
    #embedding()
    chat_openai()